﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using BarCode.Common;
using System.IO;
using BarCode.Module;
using BarCode.AccessDao;
using System.Runtime.InteropServices;
using BarCode.Bean;
using System.IO.Ports;
using System.Threading;
using MySql.Data.MySqlClient;
using System.Security.Policy;
using System.Reflection.Emit;
using System.Data.SqlClient;

namespace BarCode.Forms
{
    public partial class MainBarCode : Form
    {
        private MySqlHelper db;

        [DllImport("user32.dll")]
        public static extern bool MessageBeep(uint uType);

        private static readonly log4net.ILog LogUtil = log4net.LogManager.GetLogger(typeof(MainBarCode));

        private static string JKHeadStr = "";
        private string meterNoStart = "";
        private string meterNoEnd = "";
        private Calibrations calibrationsInfo = null;

        public MainBarCode()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Base_BarCode_Load(object sender, EventArgs e)
        {

            JKHeadStr = IniFileHelper.getStringValue("System", "JK_Header");

            lblUser.Text = GlobalVal.CurrentUser.User;
            lblStatus.Text = "当前为正常工作状态！";
            refreshWorkAmount();
           
            txtJKCode.Text = "";
            txtJKCode.Focus();
            txtMeterNo.Text = "";
            lblOrderNo.Text = "";
            lblNote.Text = "";
            lblMeterRange.Text = "";
        }

        /// <summary>
        /// 窗体关闭
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Base_BarCode_FormClosed(object sender, FormClosedEventArgs e)
        {
            //if (GlobalVal.bolNetConnect)
            //{
            //    GlobalVal.bolUploadSubMain = false;
            //    modeFunction.upload_Data("jk");
            //}
            Application.Exit();
        }


        /// <summary>
        /// 二维码输入后回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtBarCode_KeyPress(object sender, KeyPressEventArgs e)
        {
            lblStatus.Text = "";
            if (e.KeyChar == (char)13)
            {
                string inputBarCode = txtJKCode.Text;

                // 条码长度检查
                //if (inputBarCode.Length != 19)
                //{
                //    ShowInputWarn("条码信息位数不正确！应为19位。", Consts.MB_ICONASTERISK);
                //    return;
                //}

                //if (!inputBarCode.StartsWith(JKHeadStr))
                //{
                //    // 如果不是9开头的条码视为无效
                //    ShowInputWarn("无效条码信息不能扫描！", Consts.MB_ICONASTERISK);
                //    return;
                //}

                if (inputBarCode.Length == 0)
                {
                    ShowInputWarn("请先输入机壳码！", Consts.MB_ICONASTERISK);
                    return;
                }

                LogUtil.Info("机壳码查询：" + inputBarCode);
                // 机壳码判断
                // 获取Calibrations
                DB02Dao db02 = new DB02Dao(GlobalVal.serverMysqlInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                calibrationsInfo = db02.selectCalibrations(inputBarCode);
                if (calibrationsInfo == null)
                {
                    lblStatus.Text = "测试无记录";
                    lblStatus.ForeColor = Color.Red;
                    txtJKCode.Text = "";
                    txtJKCode.Focus();
                    return;
                }
                //查询program
                DB01Dao db01 = new DB01Dao(GlobalVal.serverMysqlInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                MnoprnPreInfo mnoprnPreInfo = db01.getNotes(calibrationsInfo.Program);
                if (mnoprnPreInfo == null)
                {
                    lblStatus.Text = "表型号获取失败";
                    lblStatus.ForeColor = Color.Red;
                    meterNoStart = "";
                    meterNoEnd = "";
                    txtJKCode.Text = "";
                    txtJKCode.Focus();
                    return;
                }
                Console.WriteLine("我是program---" + mnoprnPreInfo.program);
                if (mnoprnPreInfo.program.Equals("1"))
                {
                    string connectionString = IniFileHelper.ReadValue("MySql", "ZF_CONNECT");
                    SqlConnection connection = null;
                    try
                    {
                        using (connection = new SqlConnection(connectionString))
                        {
                            connection.Open();
                            string query = "SELECT BarCode FROM Zz_CbValveScan_His where BarCode = @jkCode";
                            using (SqlCommand command = new SqlCommand(query, connection))
                            {
                                command.Parameters.AddWithValue("@jkCode", inputBarCode.ToString());
                                using (SqlDataReader reader = command.ExecuteReader())
                                {
                                    if (!reader.HasRows)
                                    {
                                        lblStatus.Text = "装阀无记录";
                                        lblStatus.ForeColor = Color.Red;
                                        txtJKCode.Text = "";
                                        txtJKCode.Focus();
                                        return;
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"错误: {ex.Message}");
                    }
                    finally
                    {
                        connection.Close();
                    }
                }
                db = new MySqlHelper(GlobalVal.serverMysqlInfo.SERVICE_IP, "db_02", GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                MySqlParameter sqlParam = new MySqlParameter("@ZCH", inputBarCode);
                DataSet retSet = db.GetDataSet(CommandType.Text, "select JL from ZhongJian where ZCH = @ZCH order by CQSJ desc ", new MySqlParameter[] { sqlParam });
                if (retSet != null && retSet.Tables.Count > 0)
                {
                    DataTable dt = retSet.Tables[0];
                    if (dt.Rows.Count > 0)
                    {
                        string JL = Convert.ToString(dt.Rows[0][0]);

                        if (!"合格".Equals(JL))
                        {
                            lblStatus.Text = "密封不合格";
                            lblStatus.ForeColor = Color.Red;
                            txtJKCode.Text = "";
                            txtJKCode.Focus();
                            return;
                        }
                    }
                    else
                    {
                        lblStatus.Text = "密封不存在";
                        lblStatus.ForeColor = Color.Red;
                        txtJKCode.Text = "";
                        txtJKCode.Focus();
                        return;
                    }
                }
                else
                {
                    lblStatus.Text = "密封不存在";
                    lblStatus.ForeColor = Color.Red;
                    txtJKCode.Text = "";
                    txtJKCode.Focus();
                }
                MySqlParameter sqlParam3 = new MySqlParameter("@ZCH", inputBarCode);
                DataSet retSet3 = db.GetDataSet(CommandType.Text, "select ZZBH from ZhongJian where ZCH = @ZCH order by CQSJ desc  LIMIT 0,1 ", new MySqlParameter[] { sqlParam3 });
                if (retSet3 != null && retSet3.Tables.Count > 0)
                {
                    DataTable dt1 = retSet3.Tables[0];
                    if (dt1.Rows.Count > 0)
                    {
                        string ZZBH = Convert.ToString(dt1.Rows[0][0]);
                        if (!ZZBH.Equals("smf"))
                        {
                            MySqlParameter sqlParam2 = new MySqlParameter("@ZCH", inputBarCode);
                            DataSet retSet2 = db.GetDataSet(CommandType.Text, "select count(*) from ZhongJian where ZCH = @ZCH  and CQSJ >= DATE_SUB(NOW(),INTERVAL 12 HOUR) ", new MySqlParameter[] { sqlParam2 });
                            if (retSet2 != null && retSet2.Tables.Count > 0)
                            {
                                DataTable dt = retSet2.Tables[0];
                                if (dt.Rows.Count > 0)
                                {
                                    int JL = Convert.ToInt16(dt.Rows[0][0]);
                                    if (JL > 4)
                                    {
                                        lblStatus.Text = "密封超过4次";
                                        lblStatus.ForeColor = Color.Red;
                                        txtJKCode.Text = "";
                                        txtJKCode.Focus();
                                        return;
                                    }
                                }
                            }
                        }
                    }
                }
                
                lblOrderNo.Text = calibrationsInfo.Program;
                lblNote.Text = calibrationsInfo.MeterData10;
                string note = calibrationsInfo.Notes.Replace("左", "").Replace("右", "");
                string n = note.Trim();
                /*DB01Dao db01 = new DB01Dao(GlobalVal.serverMysqlInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                MnoprnPreInfo mnoprnPreInfo = db01.getNotes(calibrationsInfo.Program);
                if (mnoprnPreInfo == null)
                {
                    lblStatus.Text = "表型号获取失败";
                    lblStatus.ForeColor = Color.Red;
                    meterNoStart = "";
                    meterNoEnd = "";
                    txtJKCode.Text = "";
                    txtJKCode.Focus();
                    return;
                }
                string [] ste = mnoprnPreInfo.program.Split('(');
                Console.WriteLine(ste[0]);
                if (!ste[0].Equals(n))
                {
                    lblStatus.Text = "表型号不一致";
                    lblStatus.ForeColor = Color.Red;
                    meterNoStart = "";
                    meterNoEnd = "";
                    txtJKCode.Text = "";
                    txtJKCode.Focus();
                    return;
                }*/
                lblModel.Text = calibrationsInfo.Notes;
                LogUtil.Info("合格id：" + calibrationsInfo.CalibrationId + "," + calibrationsInfo.EquipmentId);
                string s = db02.checkF(calibrationsInfo.CalibrationId.ToString(), calibrationsInfo.EquipmentId.ToString());
                if ("0".Equals(s)){
                    lblStatus.Text = "测试不合格";
                    lblStatus.ForeColor = Color.Red;
                    txtJKCode.Text = "";
                    txtJKCode.Focus();
                    return;
                }
                else
                {
                    // 查询表号范围
                    //LogUtil.Info("表号范围查询：" + "02000" + calibrationsInfo.Program + "," + calibrationsInfo.MeterData10);
                    LogUtil.Info("表号范围查询：" + calibrationsInfo.Program + "," + calibrationsInfo.MeterData10);
                    //MnoprnPreInfo mnoprnPreInfo = db01.getMeterRange("02000" + calibrationsInfo.Program, calibrationsInfo.MeterData10);
                    mnoprnPreInfo = db01.getMeterRange(calibrationsInfo.Program, calibrationsInfo.MeterData10);
                    if (mnoprnPreInfo == null)
                    {
                        lblStatus.Text = "表号范围获取失败";
                        lblStatus.ForeColor = Color.Red;
                        meterNoStart = "";
                        meterNoEnd = "";
                        txtJKCode.Text = "";
                        txtJKCode.Focus();
                        return;
                    }
                    LogUtil.Info("查询成功，显示结果：" + meterNoStart + "～" + meterNoEnd);
                    meterNoStart = mnoprnPreInfo.meters_IDstart;
                    meterNoEnd = mnoprnPreInfo.meters_IDend;
                    lblMeterRange.Text = meterNoStart + "～" + meterNoEnd;

                    txtMeterNo.Focus();
                    lblStatus.Text = "请扫描表号";
                    lblStatus.ForeColor = Color.Blue;
                }

                

            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtMeterNo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                string jkCode = txtJKCode.Text;
                string inputBarCode = txtMeterNo.Text;
                LogUtil.Info("机壳码查询：" + jkCode +"，表号：" + inputBarCode);
                Console.WriteLine(meterNoStart+"-"+meterNoEnd);
                // 判断表号是否在范围内
                if (inputBarCode.CompareTo(meterNoStart) < 0 || inputBarCode.CompareTo(meterNoEnd) > 0)
                {
                    lblStatus.Text = "表号超出范围";
                    lblStatus.ForeColor = Color.Red;
                    txtMeterNo.Text = "";
                    txtMeterNo.Focus();
                    return;
                }

                // 更新表号信息
                LogUtil.Info("开始更新表号信息");
                DB02Dao db02 = new DB02Dao(GlobalVal.serverMysqlInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
                int updCnt = db02.updateMeterNo(calibrationsInfo, inputBarCode, txtJKCode.Text);
                if (updCnt == 0)
                {
                    lblStatus.Text = "更新失败，请联系管理员";
                    lblStatus.ForeColor = Color.Red;
                    txtMeterNo.Text = "";
                    txtMeterNo.Focus();
                    return;
                }

                txtJKCode.Text = "";
                txtMeterNo.Text = "";
                txtJKCode.Focus();
                lblOrderNo.Text = "";
                lblNote.Text = "";
                lblMeterRange.Text = "";
                lblModel.Text = "";

                LogUtil.Info("更新表号成功, 刷新页面工作量");
                refreshWorkAmount();
                lblStatus.Text = "保存成功，请扫描机壳码";
                lblStatus.ForeColor = Color.Blue;

            }

        }


        /// <summary>
        /// 输入有误时弹框显示
        /// </summary>
        /// <param name="msg"></param>
        private void ShowInputWarn(string msg, uint beep)
        {
            txtJKCode.Text = "";
            txtJKCode.Focus();
            lblStatus.Text = msg;
            lblStatus.ForeColor = Color.Red;
            if (beep > 0)
            {
                MessageBeep(beep);
            }
        }



        /// <summary>
        /// 获取最新工作量
        /// </summary>
        private void refreshWorkAmount()
        {
            DB02Dao db02 = new DB02Dao(GlobalVal.serverMysqlInfo.SERVICE_IP, GlobalVal.serverMysqlInfo.USERID, GlobalVal.serverMysqlInfo.USERPWD);
            int workAmount = db02.getRelateWorkAmount(GlobalVal.CurrentUser.User);
            lblAmount.Text = workAmount.ToString();
            LogUtil.Info("当前工作量：" + workAmount.ToString());
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            lblStatus.Text = "当前为正常工作状态！";

            txtJKCode.Text = "";
            txtJKCode.Focus();
            txtMeterNo.Text = "";
            lblOrderNo.Text = "";
            lblNote.Text = "";
            lblMeterRange.Text = "";
            lblModel.Text = "";
        }

        private void txtJKCode_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtMeterNo_TextChanged(object sender, EventArgs e)
        {

        }

        private void lblStatus_Click(object sender, EventArgs e)
        {

        }
    }
}
